<?php
namespace App\Services\WxMass\Factory;

use App\Facades\EasyWechat;
use App\Models\WxMassResult;
use App\Services\WxCommon\WxError;
use App\Services\WxMass\FilterFactory;


/**
 * 群发抽象类
 * @package App\Services\WxMass
 */
abstract class WxMassAbstract extends \App\Services\WxCommon\WxBase implements WxMassInterface
{
    protected $data;//资源数据

    /**
     * 构造函数
     * @param string $appid
     * @throws \Exception
     */
    public function __construct($appid = '')
    {
        parent::__construct($appid);
    }

    /**
     * 群发消息推送
     * @param $message
     * @param $rule
     */
    public function sendMass($message, $rule)
    {
        $app = EasyWechat::officialAccount($this->appid);
        $formatRule = (new FilterFactory())->createFilterObj($rule['type'])->formatOutput($rule);
        if ($formatRule['type'] == FilterFactory::OUTPUT_TYPE_ALL){
            $to = null;
        }elseif ($formatRule['type'] == FilterFactory::OUTPUT_TYPE_TAGID){
            $to = $formatRule['tagid'];
        }elseif ($formatRule['type'] == FilterFactory::OUTPUT_TYPE_TOUSER){
            $to = $formatRule['openids'];
        }else{
            throw new \Exception('无效的群发规则');
        }
        $apiRs = $app->broadcasting->sendMessage($message, $to);
        WxError::checkApiResponse($apiRs);
        return $apiRs;
    }

    /**
     * 群发消息回调处理
     * @param $eventData
     * @return bool
     */
    public function handleCallback($eventData)
    {
        \DB::beginTransaction();
        try {
            $msgId = $eventData['MsgID'] ?? 0;
            if ($msgId){
                WxMassResult::updateOrCreate(
                    ['appid'=>$this->appid, 'msg_id'=>$msgId],
                    [
                        'status' => $eventData['Status'] ?? 0,
                        'total_count' => $eventData['TotalCount'] ?? 0,
                        'filter_count' => $eventData['FilterCount'] ?? 0,
                        'sent_count' => $eventData['SentCount'] ?? 0,
                        'error_count' => $eventData['ErrorCount'] ?? 0,
                        'check_state' => $eventData['CopyrightCheckResult']['CheckState'] ?? 0,
                    ]
                );
            }
            \DB::commit();
        } catch (\Exception $e) {
            \DB::rollBack();
            throw new \Exception($e->getMessage());
        }
        return true;
    }

    /**
     * 魔术赋值方法
     * @param $name
     * @param $value
     */
    public function __set($name, $value)
    {
        $this->data[$name] = $value;
    }

    /**
     * 魔术读取属性值方法
     * @param $name
     * @return float|int
     */
    public function __get($name)
    {
        if (array_key_exists($name, $this->data)) {
            return $this->data[$name];
        }
    }
}